package com.tmzn.web;

import com.alibaba.fastjson2.JSONObject;
import com.tmzn.jwt.JwtKit;
import com.tmzn.jwt.bean.MyIJwtAble;
import com.tmzn.web.annotation.Anonymous;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class LoginInterceptor implements HandlerInterceptor {  
  
    @Override  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object handlerObj = handler;

        // 将Handler转换为HandlerMethod类型的对象
        HandlerMethod handlerMethod = (HandlerMethod) handlerObj;

        // 获取被调用的Controller方法的方法对象
        Method method = handlerMethod.getMethod();

        String name = method.getName();
        if("error".equals(name)){
            return true;
        }
        Anonymous annotation = method.getAnnotation(Anonymous.class);
        if(annotation != null){//包含该注解就不拦截
            return true;
        }
        String authorization = request.getHeader("Authorization");
        MyIJwtAble user = JwtKit.getUser(authorization);
        if(user != null){
            return true;
        }
        ServletOutputStream outputStream = response.getOutputStream();
        JSONObject object = new JSONObject();
        object.put("code",401);
        object.put("msg","no auth");
        outputStream.print(object.toString());
        outputStream.close();
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // 对于其他路径，允许继续访问
        return false;  
    }  
  
    @Override  
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {  
        // 可选方法，在请求处理完成后执行，可以用来对响应进行修改或收集共享数据  
    }  
  
    @Override  
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {  
        // 可选方法，在整个请求结束之后执行，可以用来进行清理工作  
    }  
}